package cn.flying.cloud.system.dict.service;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.flying.cloud.base.common.constants.Constants;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.redis.service.RedisService;
import cn.flying.cloud.system.dict.mapper.DictDataMapper;
import cn.flying.cloud.system.dict.model.DictData;

/**
 * 枚举字典数据
 *
 * @author admin
 * @since 2024-04-02 13:05:04
 */
@Service
public class DictDataService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private DictDataMapper dictDataMapper;
    @Resource
    private RedisService redisService;


    /**
     * 根据枚举类型查询枚举字典
     *
     * @param type
     * @return
     */
    public Map<String, String> getDict(String type) {
        String tenantId = Ft.Local.TenantId();
        Map<Object, Object> data = redisService.hmget(Constants.ENUM_PREFIX + type);
        // 命中缓存直接返回
        if (data != null && !data.isEmpty()) {
            return data.entrySet().stream().collect(Collectors.toMap(e -> String.valueOf(e.getKey()), e -> (String) e.getValue()));
        }

        List<DictData> list = dictDataMapper.getDict(type, tenantId);
        Map<String, String> map = new HashMap<>();
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        for (DictData dict : list) {
            map.put(dict.getCode(), dict.getText());
        }
        Map<String, Object> redisMap = map.entrySet().stream().collect(Collectors.toMap(e -> String.valueOf(e.getKey()), Map.Entry::getValue));

        // 缓存字典
        redisService.hmset(Constants.ENUM_PREFIX + type, redisMap);
        return map;
    }
}
